package com.ovt.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;
import com.ovt.dao.BaseDao;
import com.ovt.dao.UserDao;
import com.ovt.entity.Page;
import com.ovt.entity.User;

public class UserDaoImpl extends BaseDao implements UserDao {
	
	public User findUser(String uname, String password) {
		Connection con=getConnection();
		PreparedStatement ps=null;
		User user=null;
		//获取所有主题
		String sql = "select * from denglu where name=? and pwd=?";
		try{			
			ps = con.prepareStatement(sql);			
			ps.setString(1,uname);
			ps.setString(2,password);
			rs = ps.executeQuery();	
			if(rs.next()){
				user= new User();
				user.setUid(rs.getString("tid"));
				user.setUname(uname);
				user.setUpwd(password);
			}
		}catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(con, ps,  rs);
		}		
		return user;
	}

	@Override
	public List<User> getUserList(Page page) {
		Connection con=getConnection();
		PreparedStatement ps=null;
		List<User> users = new ArrayList<User>();
		//获取所有主题
		String sql = "select * from t_user limit ?, ?";
		try{			
			ps = con.prepareStatement(sql);
			ps.setInt(1,(page.getCurrPageNo()-1)*page.getPageSize());
			ps.setInt(2,page.getPageSize());
			
			rs = ps.executeQuery();
			
			while(rs.next()){
				User user= new User();
				user.setUid(rs.getString("sys_user_id"));
				user.setUname(rs.getString("uname"));
				user.setUpwd(rs.getString("pwd"));
				users.add(user);
			}
		}catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(con, ps,  rs);
		}
		return users;
	}

	@Override
	public int getUserListCount() {
		Connection con=getConnection();
		PreparedStatement ps=null;
		//获取所有主题
		String sql = "select count(sys_user_id) as count from t_user";
		try{
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();	
			if(rs.next()){
				return rs.getInt("count");
			}
		}catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(con, ps,  rs);
		}
		return 0;
	}

	@Override
	public boolean addUserinfor(String uname, String password) {
		Connection con=getConnection();
		PreparedStatement ps=null;
		 Statement stmt = null;
		boolean b=false;
		//获取所有主题
		String sql = "insert into t_user(uname,pwd) values('"+uname+"','"+password+"')";
		try{			
			stmt = (Statement) con.createStatement();	
			int n=stmt.executeUpdate(sql);
			if(n>0){
				b=true;
			}
			else{
				b=false;
			}
		}catch (SQLException e) {
			e.printStackTrace();
			b=false;
		}finally{
			closeAll(con, ps,  rs);
		}		
		return b;
	}	
}
